/**
 * 
 * 获取每个人的进行中的任务数量
 * 
 * 
 */

var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var jwt = utils.jwt;
var SqlHelper = utils.SqlHelper;
var User = require('./dal/user.js')

const manList = ["曾晨", "谢晓飞", "方博文", "赵伟", "居斯洋", "梁虎", "甘林", "李嘉惟", "陈锐", "邹腾", "杨阳", "柯遐能"]

const secretkey = "xfKey";
const ValidTime = 1800; // 30分钟的Token有效期
const timeNow = () => {
    return parseInt(Date.now() / 1000);
}

const checkToken = function (token) {
    // let body = req.body || req.query;

    return new Promise((resolve, reject) => {

        // 是否存在
        if (!token) {
            return resolve({ error_code: 1, msg: "无token" });
        }

        // 是否有效
        var now = timeNow();
        jwt.decode(token)
            .then((data) => {
                jwt.encode(secretkey, { 'userid': data.userid, 'exp': timeNow() + ValidTime }).then((token) => {
                    resolve({ token: token, userid: data.userid }); // 更新token
                });
            }, (err) => {
                resolve({ error_code: 1, msg: "无效token" });
            })
    })
}

/**
 * 搜索人员的进行项目个数
 */
const init = async (req, res) => {

    var body = req.body || req.query;

    var checkResult = await checkToken(body.token);
    if (checkResult.error_code) return res.send(checkResult);

    var sqls = [];
    for (let i = 0; i < manList.length; i++) {
        sqls.push('select count(*)num from admin_tasks where (backend like "%' + manList[i] + '%" or front like "%' + manList[i] + '%") and state = "进行中"');
    }

    sqls = sqls.join(' union all ');
    sqls = sqls + ";";

    var sqlHelper = new SqlHelper();
    var result = await sqlHelper.asyncQuery(sqls);

    return res.send({ manlist: manList, result: result })

}

/**
 * 搜索某个人员的所有进行中的数据
 */
const item = async (req, res) => {

    var body = req.body || req.query;

    var checkResult = await checkToken(body.token);
    if (checkResult.error_code) return res.send(checkResult);

    var sqlStr = 'select * from admin_tasks where (backend like "%' + body.name + '%" or front like "%' + body.name + '%") and state = "进行中";';

    var sqlHelper = new SqlHelper('admin_tasks');
    var results = await sqlHelper.asyncQuery(sqlStr);

    let comments = await sqlHelper.asyncComments();
    let count = await sqlHelper.asyncCount();

    return res.send({
        result: {
            list: results,
            count: count[0].num,
            comments: comments
        },
        token: checkResult.token
    })


}

var analysisFn = function (req, res) {
    var body = req.body || req.query;

    var cmd = body.cmd;

    // 命令解析
    if (!cmd) {
        return res.send({ error_code: 1, msg: '无效请求, cmd参数出错' });
    }

    switch (cmd) {
        case 'init':
            init(req, res);
            break;
        case 'item':
            item(req, res);
            break;
        default:
            return res.send({ error_code: 1, msg: '无效请求, cmd参数出错' });
    }
}

server.post({ path: routerApi, name: routerApi }, analysisFn)